const axios = require("axios")

function formatComponentProps(list) {
  const isTitleComponent = function (key) {
    return (14 <= key && key <= 17) || (38 <= key && key <= 49)
  }

  const isBackgroundComponent = function (key) {
    return key === 18 || (22 <= key && key <= 37)
  }

  // 替换新的属性名
  const replaceProps = {
    fontsize: "fontSize",
    fontcolor: "fontColor",
    fonttext: "fontText",
    fontalign: "fontStyles",
    fontposition: "fontHorizonAlign",
    backimage: "backImage",
  }

  list.forEach(com => {
    const key = Number(com.componentKey)
    if (isTitleComponent(key) || isBackgroundComponent(key)) {
      com.props.backDefaultImageName = com.props.backDefaultImageName || ""
      for (let [key, value] of Object.entries(replaceProps)) {
        if (key in com.props) {
          com.props[value] = com.props[key]
          delete com.props[key]
        }
      }
    }
  })
  return { contents: list }
}

/**
 * 根据大屏id和人员token获取大屏信息
 * @param {string} dashboardId 大屏ID
 * @param {string} token 用户token
 */
module.exports = function (dashboardId, token, env = "cn") {
  const getInfoConfig = {
    url: `https://code-dashboard-api.ctbiyi.${env}/api/dashboardContents`,
    method: "get",
    headers: {
      Authorization: token,
    },
    params: {
      dashboardId,
    },
  }

  axios(getInfoConfig)
    .then(res => {
      const config = {
        url: `https://code-dashboard-api.ctbiyi.${env}/api/dashboardContents`,
        method: "post",
        headers: {
          Authorization: token,
          "Content-Type": "application/json",
        },
        data: { ...formatComponentProps(res.data), dashboardId },
      }
      // console.log(config.data.contents.map(v => v.props))
      return axios(config)
    })
    .then(res => {
      if (res.data) {
        console.log("格式化成功")
      } else {
        console.log("格式化失败")
      }
    })
    .catch(err => {
      console.log(err)
    })
}
